package com.demo.store;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Collection;

import org.apache.log4j.Logger;

import com.demo.bean.Enviroment;
import com.demo.util.CollectionOracle;
import com.demo.util.FileBackup;
import com.demo.util.FileNameEnums;

/**
 * jdbc采用批处理 preparStatement防止sql注入
 * 
 * @author ASUS
 *
 */
public class StoreImpl implements IStore {

	private static Logger logger = Logger.getLogger(StoreImpl.class);

	/**
	 * 实现存储数据
	 * 
	 * @throws Exception
	 */
	@Override
	public void store(Collection<Enviroment> collection) throws Exception {

		Object object = FileBackup.recover(FileNameEnums.SERVER_DATA_PATH.getPath(), true);
	
		if (object != null) {
			collection.addAll((Collection<? extends Enviroment>) object);
		}

		Connection connection = CollectionOracle.getConnection();
		try {

			int num = 0;
			int day = 0;
			PreparedStatement prepareStatement = null;
			// 根据Enviroment的采集日期，获取里面的天
			logger.info("开始存储数据...");
			for (Enviroment enviroment : collection) {
				int day1 = Integer.parseInt(enviroment.getGathDate().toString().substring(8));

				if (day != day1) {
					// 上次循环，preparStatement缓存池里面还有没有执行的sql
					if (prepareStatement != null) {
						prepareStatement.executeBatch();
						prepareStatement.clearBatch();
						prepareStatement.close();
					}
					day = day1;
					// 拼接sql
					String sql = "insert into day_data_" + day + " values(common_seq.nextval,?,?,?,?,?,?,?,?,?)";
					prepareStatement = connection.prepareStatement(sql);
				}

				prepareStatement.setString(1, enviroment.getSrcId());
				prepareStatement.setString(2, enviroment.getDevId());
				prepareStatement.setLong(3, enviroment.getRegionId());
				prepareStatement.setString(4, enviroment.getName());
				prepareStatement.setLong(5, enviroment.getCount());
				prepareStatement.setInt(6, enviroment.getState());
				prepareStatement.setDouble(7, enviroment.getData());
				prepareStatement.setInt(8, enviroment.getReviceState());
				prepareStatement.setDate(9, enviroment.getGathDate());

				prepareStatement.addBatch();
				num++;
				if (num % 100 == 0) {
					prepareStatement.executeBatch();
					prepareStatement.clearBatch();
				}
			}

			// 循环结束还有没有执行的sql，以下执行
			if (prepareStatement != null) {
				prepareStatement.executeBatch();
				prepareStatement.clearBatch();
			}
			connection.commit();
			logger.info("存储数据成功！！");
			connection.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// 执行过程中可能发生异常，那么回滚所有，并且备份文件
			connection.rollback();
			logger.info("存储数据发生错误，成功的数据已经备份...");
			FileBackup.store(FileNameEnums.SERVER_DATA_PATH.getPath(), collection);
		}
	}

}
